import { login,userInfo,userProfile} from '@/api/user'
import { setToken, getToken,removeToken, setTimeStamp} from '@/utils/auth'
import {resetRouter} from '@/router'

const state = {
  token: getToken(),
  userInfo:{}
}

const mutations = {
  // 获取token
  setToken (state, token) {
    state.token = token
    setToken(token)
  },

  // 修改用户信息
  setUserInfo(state,playload){
    state.userInfo = playload
  },

  // 删除token
  removeToken(state){
    state.token = null
    removeToken()
  },

  // 删除用户信息
  removeUserInfo(state){
    state.userInfo= {}
  }
}

const actions = {
  // 发送请求获取token
  async login (context, data) {
    try {
      let res = await login(data)
      console.log(res)
      context.commit('setToken', res.data)
      setTimeStamp()
    } catch (error){
      // 来到这里说明请求失败,login就能收到失败信息
      return Promise.reject(error)
    }
  },

  // 获取用户信息
  async getUserInfo(context){
    let res = await userInfo()
    // console.log(res);
    let result = res.data
    let resImg = await userProfile(res.data.userId)
    // console.log(resImg);
    let allInfo = {
      ...res.data,
      ...resImg.data
    }
    context.commit('setUserInfo',allInfo)
    return result
  },

  // 删除用户信息
  async logout({commit,dispatch}){
    // 删除token
    commit('removeToken')
    // 删除用户信息
    commit('removeUserInfo')
    resetRouter() // 重置路由
    // 设置权限模块下路由为初始模块
    dispatch('permission/setRoutes',[],{root:true})
    dispatch('tagsView/delAllViews',null,{root:true})
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
